import request from './request';

/**
 * https://www.ietf.org/rfc/rfc6749.txt
 * OAuth 协议 4.3.1 要求格式为 form 而不是 JSON 注意！
 */
const FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded';

/**
 * 登录
 * @param data
 */
export const login = (data) => {
    const basicAuth = 'Basic ' + window.btoa('pig:pig'); // 使用默认的客户端ID和密钥
    localStorage.setItem('basicAuth', basicAuth);
    
    return request({
        url: '/auth/oauth2/token',
        method: 'post',
        data: data,
        headers: {
            skipToken: true,
            Authorization: basicAuth,
            'Content-Type': FORM_CONTENT_TYPE,
        },
    });
};

/**
 * 获取用户信息
 */
export const getUserInfo = () => {
    return request({
        url: '/admin/user/info',
        method: 'get',
    });
};

/**
 * 退出登录
 */
export const logout = () => {
    return request({
        url: '/auth/token/logout',
        method: 'delete',
    });
};

/**
 * 管理员登录方法 - 用于获取有权限的token
 */
export const adminLogin = () => {
    const data = {
        username: 'admin',
        password: 'YehdBPev',
        grant_type: 'password',
        scope: 'server'
    };
    
    return request({
        url: '/auth/oauth2/token',
        method: 'post',
        params: data,
        headers: {
            skipToken: true,
            Authorization: 'Basic ' + window.btoa('pig:pig'),
            'Content-Type': FORM_CONTENT_TYPE,
        },
    }).then(response => {
        console.log('管理员登录成功', response);
        
        // 确保正确保存token，与 pig-ui 一致
        if (response && response.access_token) {
            // 直接使用 localStorage 保存，确保与 getToken 方法一致
            localStorage.setItem('token', response.access_token);
            console.log('已保存token:', response.access_token);
            
            // 保存 refresh_token 如果有的话
            if (response.refresh_token) {
                localStorage.setItem('refresh_token', response.refresh_token);
            }
        }
        return response;
    }).catch(error => {
        console.error('管理员登录失败', error);
        throw error;
    });
};